package cn.hxzy.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.InvalidClaimException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;

/**
 * 操作jwt的工具类
 */
public class JWTUtil {
    //盐值
    public final static String KEY = "&**2rwe$#Y43rWEW";

    //生成令牌
    public static String createJwt(String userName) {
        //日历
        Calendar calendar = Calendar.getInstance();
        //设置有效期
        calendar.add(Calendar.SECOND,1800);
        //创建builder对象
        JWTCreator.Builder builder = JWT.create()
        //载荷信息
        .withClaim("userName", userName)
        //签发时间
        .withExpiresAt(calendar.getTime());
        //加密-使用盐
        String token = builder.sign(Algorithm.HMAC256(KEY));
        return token;
    }

    /*
   校验令牌
    */
    public static Claim decode(String token) {
        DecodedJWT decodedJWT = null;
        try{
            decodedJWT= JWT.require(Algorithm.HMAC256(KEY)).build().verify(token);
        }
        catch (SignatureVerificationException e){
            e.printStackTrace();
            System.out.println("签名不一致");
        }
        catch (TokenExpiredException e){
            e.printStackTrace();
            System.out.println("令牌过期");
        }
        catch (AlgorithmMismatchException e){
            e.printStackTrace();
            System.out.println("签名算法不匹配");
        }
        catch (InvalidClaimException e){
            e.printStackTrace();
            System.out.println("payload不可用");
        }
        Claim claim = decodedJWT.getClaim("userName");
        return claim;
    }

    //数据信息的解析
//    public static String parse(DecodedJWT decodedJWT) {
//        Claim claim = decodedJWT.getClaim("userName");
//        String userName = null;
//        if (!Objects.isNull(claim)) {
//            userName = claim.asString();
//        }
//        return userName;
//    }

}
